@namespace DaoHang.Components.Shared

<div class="website-icon">
    @if (!string.IsNullOrEmpty(IconUrl))
    {
        <img src="@EnsureHttpsUrl(IconUrl)" alt="@AltText" 
             onerror="this.onerror=null; this.src='@GetFallbackIcon()';" 
             class="icon-img @CssClass" />
    }
    else
    {
        <i class="@GetDefaultIconClass() @CssClass"></i>
    }
</div>

<style>
    .website-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }

    .website-icon .icon-img {
        width: 24px;
        height: 24px;
        object-fit: contain;
        border-radius: 4px;
    }

    .website-icon .bi {
        font-size: 20px;
        color: #6c757d;
    }

    /* 不同尺寸的样式 */
    .website-icon .table-icon {
        width: 32px;
        height: 32px;
    }

    .website-icon .modal-icon {
        width: 40px;
        height: 40px;
    }

    .website-icon .preview-icon {
        width: 20px;
        height: 20px;
    }

    .website-icon .recommendation-icon {
        width: 48px;
        height: 48px;
    }
</style>

@code {
    /// <summary>
    /// 图标URL
    /// </summary>
    [Parameter]
    public string? IconUrl { get; set; }

    /// <summary>
    /// 替代文本
    /// </summary>
    [Parameter]
    public string AltText { get; set; } = "";

    /// <summary>
    /// CSS类名
    /// </summary>
    [Parameter]
    public string CssClass { get; set; } = "";

    /// <summary>
    /// 确保URL使用HTTPS协议，避免混合内容问题
    /// </summary>
    /// <param name="url">原始URL</param>
    /// <returns>HTTPS URL</returns>
    private static string EnsureHttpsUrl(string? url)
    {
        if (string.IsNullOrEmpty(url))
            return string.Empty;

        // 如果是HTTP协议，转换为HTTPS
        if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
        {
            return "https://" + url.Substring(7);
        }

        // 如果是协议相对URL，添加HTTPS
        if (url.StartsWith("//"))
        {
            return "https:" + url;
        }

        return url;
    }

    /// <summary>
    /// 获取备用图标URL，使用内联base64图标避免404错误
    /// </summary>
    /// <returns>备用图标URL</returns>
    private static string GetFallbackIcon()
    {
        // 使用内联base64透明图标，避免外部文件404错误
        return "";
    }

    /// <summary>
    /// 获取默认图标类名
    /// </summary>
    /// <returns>图标类名</returns>
    private static string GetDefaultIconClass()
    {
        return "bi bi-globe";
    }
} 